<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

function retailstore_list_page()
{
    @$output = drupal_render(drupal_get_form('retailstore_list_form'));
    return $output;
}

function retailstore_list_form($form, &$form_state)
{
    $form['address_fuzzy'] = _insert_address_autocomplete($form, $form_state);
    $form['address'] = _insert_address_selection_form($form, $form_state, 'address', 5, FALSE, _get_address_id($form_state),'','',TRUE);

    $form['retailname'] = array(
        '#attributes' => array('placeholder' => '基层商姓名'),
        '#title_display' => 'before',
        '#type' => 'textfield',
        '#default_value' => !empty($form_state['values']['retailname']) ? $form_state['values']['retailname'] : '',
    );
    $form['telephone'] = array(
        '#attributes' => array('placeholder' => '电话'),
        '#type' => 'textfield',
        '#suffix' => '</div>',
        '#maxlength' => 15,
        '#default_value' => !empty($form_state['values']['telephone']) ? $form_state['values']['telephone'] : '',
    );
    $form['brand']=_insert_brand_name_selection_form($form, !empty($form_state['values']['brand']) ? $form_state['values']['brand'] : '');
//    $fields = array(
//        '' => '请选择',
//        'sales_1' => '销量',
//    );
//    numerical_range_search($form,$fields);
    $table['#markup'] =  data_list_view_page($form, $form_state);
    ajax_submit_form($form,$form_state,$table,'');

    return $form;
}

function retailstore_list_form_validate($form, &$form_state)
{
}

function data_list_view_page($form = '', &$form_state = '')
{
        global $user;
        $output = '';
        //表头
        $header = array(
            array('data' => '选择', 'class' => ['essential no']),
            array('data' => '序号', 'class' => ['essential no'], 'field' => 'retailstore_id'),
            array('data' => '基层商姓名', 'class' => ['essential store-name']),
            array('data' => '省 市 县', 'class' => ['essential province city county']),
            array('data' => '电话', 'class' => ['essential phone']),
            array('data' => '操作', 'class' => ['essential more']),
        );
        $query = db_select('addr', 'A')->extend('PagerDefault')->extend('TableSort');
        $query->join('retailstore', 'S', 'A.addr_id=S.addr_id');


        //地址级别查询
       _address_search_conditon($query,$form_state);


        if(!user_access('view all retailstore') && user_access('view own retailstore')){
            $query->condition('S.author_uid',$user->uid, '=');
        }
        //模糊条件筛选

        if (!empty($form_state['values']['retailname'])) {//模糊店铺名字查询条件
            $query->condition('S.name', '%' . db_like($form_state['values']['retailname']) . '%', 'LIKE');
        }
        if (!empty($form_state['values']['telephone'])) {//模糊电话号码查询条件
            $query->condition('S.phone', '%' . db_like($form_state['values']['telephone']) . '%', 'LIKE');
        }
        $query->fields('S', array('retailstore_id', 'name', 'phone', 'author_uid'));
        $query->leftJoin('addr', 'A1', 'A.province_id=A1.addr_id');
        $query->leftJoin('addr', 'A2', 'A.city_id=A2.addr_id');
        $query->leftJoin('addr', 'A3', 'A.county_id=A3.addr_id');
        $query->addField('A1', 'name', 'province');
        $query->addField('A2', 'name', 'city');
        $query->addField('A3', 'name', 'county');
        if(!empty($form_state['values']['field'])){
            if(!empty($form_state['values']['min_number']) && !empty($form_state['values']['max_number'])){
                $db_and = db_and();
                $db_and->condition('S.'.$form_state['values']['field'], $form_state['values']['min_number'], '>');
                $db_and->condition('S.'.$form_state['values']['field'], $form_state['values']['max_number'], '<');
                $query->condition($db_and);
            }elseif(!empty($form_state['values']['min_number'])){
                $query->condition('S.'.$form_state['values']['field'], $form_state['values']['min_number'], '>');
            }elseif(!empty($form_state['values']['max_number'])){
                $query->condition('S.'.$form_state['values']['field'], $form_state['values']['max_number'], '<');
            }
        }
        if(!empty($form_state['values']['brand'])){
            $or = db_or();
            $or->condition('S.brands',$form_state['values']['brand'].',%','LIKE');
            $or->condition('S.brands','%,'.$form_state['values']['brand'],'LIKE');
            $or->condition('S.brands','%,'.$form_state['values']['brand'].',%','LIKE');
            $or->condition('S.brands',$form_state['values']['brand'],'LIKE');
            $query->condition($or);
        }
        if(empty($form_state['values']) || empty($form_state['values']['order'])) {
            $query->orderBy('S.timestamp', 'DESC');
        }
        $query->limit(variable_get("list_page_item_number", 5));

        $retailstoreInfo = $query->orderByHeader($header)->execute();

        $rows = array();
        //表内容
        $n = 1;
        foreach ($retailstoreInfo as $row) {
            $city = $row->city ? '  '.$row->city :'';
            $county = $row->county ? '  '.$row->county :'';
            $town = $row->town ? '  '.$row->town :'';
            $village = $row->village ? '  '.$row->village :'';
            if (nonghua_user_access('retailstore', 'delete', $row->retailstore_id, $row->author_uid, 0)) {
                $disabled = ' class="listViewTableCheck" ';
            } else{
                $disabled = ' disabled="true" ';
            }
            $rows[] = array(
                array('data' => "<input type='checkbox'".$disabled." value ='" . $row->retailstore_id . "' name='" . $row->retailstore_id . "'/>" . $n++, 'class' => 'integrant essential no'),
                array('data' => $row->retailstore_id, 'class' => ['essential no']),
                array('data' => $row->name, 'class' => ['integrant essential store-name']),
                array('data' => $row->province.$city.$county.$town.$village, 'class' => ['integrant haveTobr essential province city county']),
                array('data' => $row->phone, 'class' => ['integrant goRight essential phone']),
                array('data' => '<a href="'.base_path().'retailstore/edit/' . $row->retailstore_id . '" data-toggle="modal" target="_top"><img width="20px" height="20px" src="'.base_path().'sites/all/themes/tweme/images/images/cz.png"/></a>', 'class' => 'essential more'),
            );
        }


        $output .= theme('table', array('header' => $header, 'rows' => $rows, 'empty' => t('没有记录'), 'attributes' => array('class' => array('table table-bordered table-striped table-hover enhanced')))); //表格
        /*	 * *按钮** */
        if(sizeof($rows) > 0 && (user_access('delete own retailstore') ||  user_access('delete all retailstore'))) {
            $output .= '<a href="javascript:void(0)" id="listViewTableSelectAll" data-toggle="modal" class="btn btn-mini">全选</a>';
            $output .= '<a href="javascript:void(0)" id="listViewTableDeleteSelected" data-toggle="modal" class="btn btn-mini">删除所选</a>';
        }
        if(!empty($form_state['values']['village'])){
            $addr_id = $form_state['values']['village'];
            $str = 'village=';
        }elseif(!empty($form_state['values']['town'])){
            $addr_id = $form_state['values']['town'];
            $str = 'town=';
        }elseif(!empty($form_state['values']['county'])){
            $addr_id = $form_state['values']['county'];
            $str = 'county=';
        }elseif(!empty($form_state['values']['city'])){
            $addr_id = $form_state['values']['city'];
            $str = 'city=';
        }elseif(!empty($form_state['values']['province'])){
            $addr_id = $form_state['values']['province'];
            $str = 'province=';
        }
        $str .= $addr_id;
        $output .= '<a href="'.base_path().'retailstore/export?'.$str.
            '&address_fuzzy='.$form_state['values']['address_fuzzy'].
            '&fuzzy_address='.$form_state['values']['fuzzy_address'].
            '&retailname='.$form_state['values']['retailname'].
            '&telephone='.$form_state['values']['telephone'].
            '&brand='.$form_state['values']['brand'].

            '" data-toggle="modal" class="btn btn-mini">导出</a>';
        $output .= theme('pager');
        return $output;
}

function retailstore_delete()
{
    ajax_table_delete('retailstore', 'retailstore_id');
}


function retailstore_export($form,&$form_state){
    $letter = array('A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z');
    $tableheader = array('地址','作物','化肥品牌','基层商姓名','详细地址','电话','门头长度','门头高度','种植面积');
    $data = get_retailstore_data($form, $form_state);
    nonghua_php_excel($letter,$tableheader,$data,'门店信息数据');
}

function get_retailstore_data($form = '', &$form_state = ''){
    global $user;
    $user_info = _get_user_info($user->uid);
    $query = db_select('addr', 'A');
    $query->join('retailstore', 'S', 'A.addr_id=S.addr_id');
    _address_search_conditon_for_export($query);

    if(!user_access('view all retailstore') && user_access('view own retailstore')){
        $query->condition('S.author_uid',$user->uid, '=');
    }
    //模糊条件筛选
    if (!empty($_GET['fuzzy_address'])) {//模糊地址查询条件
        $query->condition('A.addr_details', '%' . db_like($_GET['fuzzy_address']) . '%', 'LIKE');
    }
    if (!empty($_GET['retailname'])) {//模糊店铺名字查询条件
        $query->condition('S.name', '%' . db_like($_GET['retailname']) . '%', 'LIKE');
    }
    if (!empty($_GET['telephone'])) {//模糊电话号码查询条件
        $query->condition('S.phone', '%' . db_like($_GET['telephone']) . '%', 'LIKE');
    }
    $query->leftJoin('addr', 'A1', 'A.province_id=A1.addr_id');
    $query->leftJoin('addr', 'A2', 'A.city_id=A2.addr_id');
    $query->leftJoin('addr', 'A3', 'A.county_id=A3.addr_id');
    
    if(!empty($_GET['field'])){
        if(!empty($_GET['min_number']) && !empty($_GET['max_number'])){
            $db_and = db_and();
            $db_and->condition('S.'.$_GET['field'], $_GET['min_number'], '>');
            $db_and->condition('S.'.$_GET['field'], $_GET['max_number'], '<');
            $query->condition($db_and);
        }elseif(!empty($_GET['min_number'])){
            $query->condition('S.'.$_GET['field'], $_GET['min_number'], '>');
        }elseif(!empty($_GET['max_number'])){
            $query->condition('S.'.$_GET['field'], $_GET['max_number'], '<');
        }
    }
    if(!empty($_GET['brand'])){
        $or = db_or();
        $or->condition('S.brands',$_GET['brand'].',%','LIKE');
        $or->condition('S.brands','%,'.$_GET['brand'],'LIKE');
        $or->condition('S.brands','%,'.$_GET['brand'].',%','LIKE');
        $or->condition('S.brands',$_GET['brand'],'LIKE');
        $query->condition($or);
    }
    $query->addField('A1', 'name', 'province');
    $query->addField('A2', 'name', 'city');
    $query->addField('A3', 'name', 'county');
    $query->fields('S', array('plants','brands','name', 'addr_details','phone', 'width','height', 'farm_area'));
    $retailstoreInfo = $query->execute()->fetchAll();
    foreach($retailstoreInfo as $k => $v){
        $retailstoreInfo[$k]->province= $v->province.$v->city.$v->county;
        unset($retailstoreInfo[$k]->city);
        unset($retailstoreInfo[$k]->county);
    }
    return $retailstoreInfo;
}